package Fly.example.filter;


import Fly.example.common.BaseContext;
import Fly.example.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/*
 * 检查用户是否登录
 * */
@Slf4j
@WebFilter(urlPatterns = "/*") //拦截所有请求
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符的写法
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到{}这个页面", request.getRequestURI());

        String Url = request.getRequestURI();
        //定义不需要拦截的数据
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
        };
        if (check(urls, Url)) {
            log.info("放行");
            log.info("本次请求不需要拦截");
            filterChain.doFilter(request, response);
            return;
        }
        //如果已经登录，则直接放行
        //后台端
        if (request.getSession().getAttribute("employee") != null) {
            //如果session不等于空，则表示已经登陆，放行
            log.info("本次请求不需要拦截");
            Long empid = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentid(empid);
            filterChain.doFilter(request, response);
            return;
        }

        //如果已经登录，则直接放行
        //移动端
        if (request.getSession().getAttribute("user") != null) {
            //如果session不等于空，则表示已经登陆，放行
            log.info("本次请求不需要拦截");
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentid(userId);
            filterChain.doFilter(request, response);
            return;
        }

        //如果未登录则返回未登录的数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /*路径匹配，检查我们的路径是否需要拦截*/
    public boolean check(String[] Usls, String requestURI) {
        for (String Url : Usls) {
            if (PATH_MATCHER.match(Url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
